/**
 * LY.com Inc.
 * Copyright (c) 2004-2019 All Rights Reserved.
 */
package com.gitee.kamismile.stoneComEx.common.component.aop;

import com.gitee.kamismile.stone.commmon.util.JsonUtil;
import com.gitee.kamismile.stoneComEx.common.component.support.annotation.LogWatch;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.lang.reflect.Method;
import java.text.MessageFormat;

/**
 * @author dong.li
 * @version $Id: LogWatchAOP, v 0.1 2019/3/1 17:01 dong.li Exp $
 */

@Aspect
@Component
public class LogWatchAOP {

    protected final Logger logger =LoggerFactory.getLogger(getClass());


    @Around("@annotation(com.gitee.kamismile.stoneComEx.common.component.support.annotation.LogWatch)")
    public Object log(ProceedingJoinPoint point) throws Throwable {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object[] args = point.getArgs();
        LogWatch logWatch = method.getAnnotation(LogWatch.class);
        Object result = point.proceed();
        stopWatch.stop();
        String className = point.getSignature().getDeclaringType().getName();
        if ((result instanceof Void) || logWatch.result() == 0) {
            logger.info(MessageFormat.format("{0} 方法{1}执行时间{2} 参数{3}", className, point.getSignature().getName(), stopWatch.getLastTaskTimeMillis(), JsonUtil.toJson(args)));
            return result;
        }
        logger.info(MessageFormat.format("{0} 方法{1}执行时间{2} 参数{3} 结果{4}", className, point.getSignature().getName(), stopWatch.getLastTaskTimeMillis(), JsonUtil.toJson(args), JsonUtil.toJson(result)));
        return result;
    }
}
